<?php 
    require_once ("/mnt/sdcard/www/Includes/simplecms-config.php"); 
    require_once  ("/mnt/sdcard/www/Includes/connectDB.php");
    include("/mnt/sdcard/www/Includes/header.php"); 

    if (isset($_POST['submit'])){
        $username = $_POST['username'];
        $password = $_POST['password'];
        $team = $_POST['team'];
        $name = $_POST['name'];

        $query = "SELECT * FROM users WHERE username='$username'";
        //$query = "SELECT * FROM deviceInfo WHERE deleted = '0'";
        $statement = $databaseConnection->prepare($query);
        $statement->execute();
        $statement->store_result();

        $creationWasSuccessful = $statement->affected_rows >= 1 ? true : false;
        if(!$creationWasSuccessful)
        {
            $query = "INSERT INTO users (username, password, team, name, registerTime) VALUES (?, SHA(?), ?, ?, Now())";

            $statement = $databaseConnection->prepare($query);
            $statement->bind_param('ssss', $username, $password, $team, $name);
            $statement->execute();
            $statement->store_result();

            $creationWasSuccessful = $statement->affected_rows == 1 ? true : false;
            if ($creationWasSuccessful)
            {
                $userId = $statement->insert_id;

                $addToUserRoleQuery = "INSERT INTO users_in_roles (user_id, role_id) VALUES (?, ?)";
                $addUserToUserRoleStatement = $databaseConnection->prepare($addToUserRoleQuery);

                // TODO: Extract magic number for the 'user' role ID.
                $userRoleId = 2;
                $addUserToUserRoleStatement->bind_param('dd', $userId, $userRoleId);
                $addUserToUserRoleStatement->execute();
                $addUserToUserRoleStatement->close();

                $_SESSION['userid'] = $userId;
                $_SESSION['username'] = $username;
                $_SESSION['team'] = $team;
                $_SESSION['name'] = $name;
                header ("Location: index.php");
            }
            else
            {
                echo "
                <div class='alert alert-danger'>
                    <strong>가입 실패!</strong> 오류로 인해 가입에 실패했습니다. 다시 시도해 주세요.<br>
                    문제가 지속될 경우, 개발자에게 문의해 주세요.
                </div>
            ";
            }
        }
        else
        {
            echo "
                <div class='alert alert-danger'>
                    <strong>가입 실패!</strong> [$username]은(는) 이미 등록된 아이디 입니다. 다른 아이디를 사용해 주세요.
                </div>
            ";
        }
    }
?>

<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            </button>
            <?php
                if (logged_on())
                {
                    $url = "/phoneList.php";
                }
                else
                {
                    $url = "/index.php";
                }
            ?>
            <a class="navbar-brand" href="<?php echo $url ?>">Device Management System</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li class="active"><a href="/index.php">Home</a></li>
                <?php
                    if (logged_on())
                    {
                        echo '
                            <li><a href="/phoneList.php">기기목록</a></li>
                            <li><a href="/approval.php">결재</a></li>
                        ';
                    }
                ?>
                <?php
                    if (is_admin())
                    {
                        echo '
                            <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">관리메뉴<b class="caret"></b></a>
                                <ul class="dropdown-menu">
                                    <li><a href="/phoneEnroll.php">기기등록</a></li>
                                    <li><a href="/manage.php">기기관리</a></li>
                                    <!--<li class="divider"></li>
                                    <li class="dropdown-header">Nav header</li>
                                    <li><a href="#">Separated link</a></li>
                                    <li><a href="#">One more separated link</a></li>-->
                                </ul>
                            </li>
                        ';
                    }
                ?>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <?php
                    if (logged_on())
                    {
                        if (is_admin())
                        {
                            echo "
                                <li><a href='#'>환영합니다, {$_SESSION['username']}(관리자)</a></li>
                                <li><a href='/logoff.php'>로그아웃</a></li>
                            ";
                        }
                        elseif (is_member())
                        {
                            echo "
                                <li><a href='#'>환영합니다, {$_SESSION['username']}(정회원)</a></li>
                                <li><a href='/logoff.php'>로그아웃</a></li>
                            ";   
                        }
                        else
                        {
                            echo "
                                <li><a href='#'>환영합니다, {$_SESSION['username']}(준회원)</a></li>
                                <li><a href='/logoff.php'>로그아웃</a></li>
                            ";
                        }
                    }
                    else
                    {

                    }
                ?>
            </ul>
        </div><!--/.navbar-collapse -->
    </div>
</div>

<div class="container">
    <form class="form-group col-lg-2" action="register.php" method="post">
        <h2 class="form-signin-heading">회원가입</h2>
        <input type="text" name="team" class="form-control" placeholder="팀 (ex: QA팀)" autofocus>
        <input type="text" name="name" class="form-control" placeholder="이름">
        <input type="text" name="username" class="form-control" placeholder="아이디">
        <input type="password" name="password" class="form-control" placeholder="비밀번호">
        <button class="btn btn-lg btn-primary btn-block" type="submit" name="submit">가입하기</button>
    </form>
</div>

<?php
    include ("/mnt/sdcard/www/Includes/footer.php");
?>